
var instance       = new Array();
var tools          = new Array();
var effects        = new Array();
var SELECTEDTOOL   = "Marquee";
var SELECTEDFILTER =  0;
var SELECTEDLAYER  = -1;  
var SELECTEDCOLOR  = -1;  
var MAXBRUSHES     = 200;
var tracers        = 0;
var customcolor    = "";

var BRUSH_REFRESH  = 1;
var BRUSH_RELOCATE = 2;
var BRUSH_RESIZE   = 3;
   
// objects --------------------------------------------------------------'
function effect (){
	this._name       = "";
	this._desc       = "";
	this._color      = "";
	this._level      = ""; 
} 

function editedfile (n,p,z,f) {
    this._name   = n;
    this._path   = p;
    this._zoom   = z;
    this._title  = filetitle(n);
    this._active = f; 
}


function tool() {
    this._icon      = "";
    this._brush     = "";
    this._color     = false;
    this._stroke    = false;
    this._fill      = false;
    this._pen       = false;
    this._font      = false;
	this._filter    = false;
    this._mousedown = null;
    this._mousemove = null;
    this._mouseup   = null;
	this._onload    = null;
	this._change    = null;
	this._send      = null;
	this._after     = null;
    this._penspan   = 1;
	this._request   = "";
	this._rotate    = "";
	this._cache     = "";
	this._desc      = "";
	this._x         = 0;
	this._y         = 0;
}
 

function historypoint (i,d) { // historypoint
   this._index = i;
   var a = d.split ("&")
   var b = new Array();
   for (var k=0;k<a.length;k++) {
       nv = a[k].split ("=");
       b[nv[0]]=nv[1];
	   b[b.length]=nv[1];
   }
   this._data  = b;
} // historypoint

// functions ------------------------------------------------------------'
/*
var debugwindow = false;
var debugdata = new Array();


function addtolog (title,content) {
	try {
		debugwindow.blur();
		debugwindow.additem (title,content);
	} catch(ex) {
        debugdata = new Array();
		// opendebug ();
	}
	
}
 
function opendebug () {
	var html="<html>";
    html += "<style>\nbody,td{font:8pt tahoma}"; 
    html += "</style>\n"; 
    html += "<body style='border:solid 1px buttonface' bgcolor='buttonface' >"; 
    html += "Last Call<input size=40 id=ilastcall>";
    html += "<div id='dlist' style='width:100%;background-color:white;height:300;overflow:auto;border:inset 1px'>"; 
    html += "</div>";
    html += "</html>";
	debugwindow = window.open ("about:blank",null,"width=600,height=340");
	debugwindow.document.write (html);
	debugwindow.opener = self;
	 
	
	
	debugwindow.additem = function (title,content) {
	  var d=new debugpoint(title,content);
	  
	  if (content.caller) {
			 cs = content.caller.toString() 
			 if (cs.indexOf("{")>0) cs = cs.substr( 0,cs.indexOf("{") );
		   d._caller =   cs
	   }
	 //  d._arguments = content.arguments;
		debugdata[debugdata.length] = d;
		var html = "<table width=100% cellpadding=2 cellspacing=1 bgcolor=green>"
		for (var z=debugdata.length-1;z>=0;z--) {
			 html += "<tr>"
			 html += "<td bgcolor=white>"
			 html += z+". <u style=color:firebrick>"+debugdata[z]._title + "</u>(";
			 a="";
			 for (var k=0;k<debugdata[z]._arguments.length;k++) {
				 a+= (a==""?"":",")+debugdata[z]._arguments[k];
			 }
			 html += a+")<br>"+debugdata[z]._caller;
			 html += "</td>"
			 html += "</tr>"
		}
		html += "</table>";
		debugwindow.ilastcall.value = title;
		debugwindow.dlist.innerHTML = html;
					
	}
}

function clean(i) {
	   return i.replace(/>/g,"&gt;").replace(/</g,"&lt;")
}
function debugpoint(t,f,c) {
    var args = new Array();
	this._title    = t;
	this._function = f;
	for (var z=0;z<f.arguments.length;z++) {
		 args[z] = f.arguments[z];
	}
	this._arguments = args;
	this._caller   = c;
}

*/



function domport(i) {
	location.href="fmgr.php?f="+i
}
function grab (i) { // grab
    var d=MM_findObj,O=d("optionspanel"),D=d("tooldesc"),B=d("brushpanel");

     addtolog("grab",grab);
	 
	var html = "";
    SELECTEDTOOL = i;
    tracers = 0;
    
	// highlight selected cell
    for (var e=0;e<tools.length;e++) 
	     d ("cell"+tools[e]._brush).bgColor = SELECTEDTOOL==tools[e]._brush?"yellow":"white"; 
	
	// read tool properties
	var grabbed_tool = tools[i];
	if ((grabbed_tool._color)&&(customcolor!="")) grabbed_tool._color=customcolor;
	var o = grabbed_tool._onload;
	var c = grabbed_tool._color;
	var p = grabbed_tool._pen; 
	
    // draw option panel containers
	if (o) html += "<div id='dopt"+grabbed_tool._brush+"'></div>";	 
	if (c) html += "<div id=dcolor></div>";
	if (p) html += "<div id=dpen></div>"; 
	
	// load panel container and description
	O.innerHTML = html; 
	D.innerHTML = grabbed_tool._desc;
	
	// load colors and pens
	if (c) grid (c.substr(0,2),c.substr(2,2),c.substr(4,2)); 
	if (p) setpen (p); 
	else { // if the tool has no pen, load a brush from the server
	    B.innerHTML = "<img src='thumbnail.php?b="+SELECTEDTOOL+"&p=1'>";
		hidestatus();
	} 
	
	// fire tool onload event
	if (o) grabbed_tool._onload();
	
	// update the zoom panel
	gozoom();	
	
	// size tooltable spacers
	heirsize("sptooltable")
} // grab

 
function makepanel(title, caption, content, expanded) { // makepanel

   //  addtolog("makepanel",makepanel);
	 
    var html = ""; // create a standard panel
    html += "<table id='"+title+"' width=200 cellpadding=0 cellspacing=0>";
    html += "  <tr bgcolor='"+(expanded?"aliceblue":"white")+"'>";
    html += "    <td width='12' bgcolor='white'>"; 
    html += "      <img src='index.php?i="+(expanded?"o":"p")+"' align='absmiddle' onclick=\"rollup('"+title+"')\" id='im"+title+"'>";
    html += "      <input id=ck"+title+" type=checkbox "+chk(expanded)+" style='display:none'>";
    html += "    </td>";
    html += "    <td>";
    html += "      &nbsp;<a href=\"javascript:rollup('"+title+"')\" style='font:7pt arial;color:blue'><u>"+caption+"</u></a>";
    html += "    </td>";
    html += "  </tr>"
    html += "  <tr "+(expanded?"":"style='display:none'")+">";
    html += "    <td width='12' align=center bgcolor='white'>"; 
    html += "      <img src='index.php?i=a' onload='heirsize(\"sp"+title+"\")'  align='absmiddle' width='1' id='sp"+title+"'>";
    html += "    </td>";
    html += "    <td bgcolor='white' align='center' style='padding:2px'>"
    html += content;
    html += "     </td>";
    html += "  </tr>";
    for (z=4;z<makepanel.arguments.length;z++) {
        html += "  <tr "+(expanded?"":"style='display:none'")+">";
        html += "    <td width='12' align=center bgcolor='white'>"; 
        html += "      <img src='index.php?i=a' onload='heirsize(\"sp"+title+"\")' align='absmiddle' width='1' id='sp"+title+"'>";
        html += "    </td>";
        html += "    <td bgcolor='white' align='center' style='padding:2px'>"
        html += makepanel.arguments[z];
        html += "     </td>";
        html += "  </tr>"; 
    }
    html += "</table>" 
    return html;
} // makepanel

function heirsize (i) { // heirsize
    var c=MM_findObj;s=c(i);
   if (s) { 
       if (s.length) {
           for(e=0;e<s.length;e++) s[e].height=s[e].offsetParent.offsetHeight; 
       } else if (s.offsetParent) s.height=s.offsetParent.offsetHeight; 
   }
} // heirsize



function loadtracers (z) { // loadtracers
     addtolog("loadtracers",loadtracers);
   showstatus ("Loading brushes...");
   window.setTimeout ("loadtracersex()",100);
} // loadtracers

function logtracers () { // logtracers
    tracers ++; 
    if (tracers>MAXBRUSHES*.9) hidestatus()
} // logtracers

function tracerfx(d,x,y,w,h) { 
   MM_findObj(d).style.top = y;
   MM_findObj(d).style.left = x;
   if (w) MM_findObj (d).width  = w;
   if (h) MM_findObj (d).height  = h;
	
}

function loadtracersex (z,r) { // loadtracersex
	 
	
   var fx="",i=z||MAXBRUSHES,R=r||BRUSH_REFRESH,d=MM_findObj,ed=d('dworkspace');
   var t=tools[SELECTEDTOOL],REPLACE_MARKUP=0;
   
	// commands[commands.length] = z+","+R;
	// contents[contents.length] = loadtracersex;
    // addtolog("loadtracersex",loadtracersex);
   
	var timeindex = new Date()
    timeindex = timeindex.getMilliseconds()
   /* 
    var BRUSH_REFRESH  = 1;
    var BRUSH_RELOCATE = 2;
    var BRUSH_RESIZE   = 3;
    if ((R==BRUSH_REFRESH)&&(i==MAXBRUSHES)) tracepanel.innerHTML = ""; */
   document.title = "MAXBRUSHES: "+MAXBRUSHES+",tracers: "+tracers+",R: "+R;
   
   if (t._pen) {
       MB = MAXBRUSHES * t._penspan;
	   
       // if the color has changed, force brush load
       if (SELECTEDCOLOR!=t._color) R=BRUSH_REFRESH;
	   
       // if there are no brushes loaded, force brush load
	   if (!d ("itx0")) R=BRUSH_REFRESH;  
	   P = isNaN(t._pen)?1:t._pen*Hoffset;
	   if ((tracers>0)&&(R==BRUSH_RELOCATE)) { // on paint complete relocate the tracers
		  // d("tracepanel").style.display="none";
		   for (var f=i-MB;f<i;f++) { 
		       tX = docx(ed);tY=docy(ed)+ed.offsetHeight; 
			   tracerfx("tr"+f,f+tX,tY); 
		   } 
	   } else if ((tracers>0)&&(R==BRUSH_RESIZE)) { // on brush resize, resize the brushes
		   for (var f=i-MB;f<i;f++) { 
		       d ("itx"+f).width  = P;
		       d ("itx"+f).height = P;
		   }  
	   }  else {  // for fresh loads and tool/color changes, load fresh brushes
	       R=BRUSH_REFRESH; // from the server
		   SELECTEDCOLOR = t._color;
		   if (t._pen!="X")  {
		       // wsdl ("b=tracer&c="+(t._color?t._color:"FFFFFF")+"&p="+t._pen);
		       wsdl ("b=tracer&c="+(t._color?t._color:"FFFFFF")+"&p=50");
		       tracers = 0;  
		   }
		   for (var f=i-MB;f<i;f++) {
		        tX  = docx(ed);tY=docy(ed)+ed.offsetHeight; 
		        Ix = d("itx"+f);
		        if (Ix&&(t._pen!="X")) {  /*  */
		            with (Ix) {
		               src = "images/brush.gif?ze="+timeindex;
		               width  = P;
		               height = P;
					   d ("tr"+f).style.left = f+tX;
					   d ("tr"+f).style.top  = tY;
		            }
		            REPLACE_MARKUP = 1;
		        } else {
				    fx += "<div id=tr"+f+" style='position:absolute;top:"+tY+";left:"+(f+tX)+";'>";
				    fx += t._pen=="X"?"<font color='#FF0000'>+</font>":"<img id='itx"+f+"' width='"+P+"' height='"+P+"' onload=logtracers() src='images/brush.gif?ze="+timeindex+"'>";
				    fx += "</div>";
				} //
		   }		  
		   if (t._pen=="X") hidestatus();
		   if (REPLACE_MARKUP==0) d("tracepanel").innerHTML = fx; 
	   }
   }  
   if (R!=BRUSH_REFRESH) hidestatus();
} // loadtracersex
 
 
function closePic(a,b) { // closePic
     addtolog("closePic",closePic);
    var A = new Array(); 
    for (var j=0;j<instance.length;j++) {
        if (instance[j]._name!=a) {
	        A[A.length]=instance[j];
		    A[instance[j]._name]=instance[j];
        }
    }
    instance=A;
    if (instance.length>0) { 
	    h=location.href.split ("?")
	    H=h[1]+"&remove="+b 
	    wsdlex (H,"index.php");
	    N=a==FILE?0:FILE; 
    } else fb_edit ("e",""); 
} // closePic

function openPic(a,b) { // openPic
   
    var d=MM_findObj;M=d("mainpic");
	M.onload = null;
	M.src = "gen.jpg";
    for (var j=0;j<instance.length;j++)  instance[j]._active=false
	FILE=a;IMAGEPATH=b;
 //   alert (FILE)
    // save current zoom setting
    instance[FILE]._zoom = Hoffset;
    
    // update current file selection
	instance[FILE]._active=true
	CACHEDIMAGE=null;
	
	// save selection data to server
	h=location.href.split ("?")
	H=h[1]+"&select="+b+"&zoom="+Hoffset; 
  
	showstatus ( wsdlex (H,"index.php") );
	
	// reset zoom to new setting
	Hoffset = instance[FILE]._zoom;
	
	// reload the image
	sizepic ();
} // openPic

function openDir(i) {
   var d=i.substr(0,i.lastIndexOf("/"));
   fb_edit('e','b','d',d,'efile',i);
}

function refreshFiles () { // refreshFiles
     addtolog("refreshFiles",refreshFiles);
    var d=MM_findObj;M=d("dfilelist");
	html = "";
	html += "<span style='background-color:#000099;padding:2px;color:white;height:32px";
	html += "border:solid 1px gray;border-color:gray white white gray;'>&nbsp;";
	html += "<img src='images/logo.jpeg' height=32 align=absmiddle border='1'>&nbsp;The<b>PIMP</b></span>";
	for (var j=0;j<instance.length;j++) { 
		 if (instance[j]._active) {
			html += "<span style='background-color:#FFFFCC;padding:2px;'>&nbsp;";
		 } else {
			 html += "<span style='background-color:#99CCFF;padding:2px;color:white;";
			 html += "border-left:solid 1px gainsboro;border-right:solid 1px gray;";
			 html += "border-top:solid 1px gainsboro;'>&nbsp;";
		 }
		// html += "<a href=\"javascript:openPic('"+instance[j]._name+"','"+instance[j]._path+"')\""; 
		// html += "><img height=32 src='thumbnail.php?i="+instance[j]._path+"&h=32' align='absmiddle' border='1' alt='open'></a>"; 
		 html += "<a href=\"javascript:openPic('"+instance[j]._name+"','"+instance[j]._path+"')\""; 
		 html += ">"+instance[j]._title+"</a>&nbsp;";
		/* html += "<a href=\"javascript:openDir('"+instance[j]._path+"')\""; 
		 html += "><img width=16 height=16 src='index.php?i=m' align='absmiddle' border='0' alt='open this folder'></a>";  */
		 html += "<a href=\"javascript:closePic('"+instance[j]._name+"','"+instance[j]._path+"')\"";
		 html += " style='font-family:webdings'>r</a>"; 
		// html += "><img src='index.php?i=e' align='absmiddle' border='0' alt='close'></a>"; 
		 html += "</span>"; 
	} 
	M.innerHTML = html;
} // refreshFiles 
 
// options panels ------------------------------------------------------------' 
function setpen (P) { // setpen
     addtolog("setpen",setpen);
   var html="",w=1,d=MM_findObj,ck=d("ckpentable"),bon=ck?ck.checked:true,R=d("dpen"),B=d("brushpanel"),T=tools[SELECTEDTOOL]; 
   T._pen = P; 
   if (P=="X") { 
	   B.innerHTML = "<img onload='loadtracers ();gozoom();' src='thumbnail.php?b="+T._brush+"'>";
   } else {
   
	   var C = T._color?T._color:""; 
	   
	   p = isNaN(T._pen)?1:T._pen*Hoffset;
	   
	   html = "<img border=0 src='thumbnail.php?b=brushes&p="+P+"&c="+C+"'onload=\"heirsize('sppentable')\" usemap='#penmap'>";
	   html = makepanel('pentable', 'Choose pen size', html, bon); 
	  
	   html += "<map name='penmap'>" // draw pen selector image map 
	   for (i=0;i<10;i++) {
		  x=20+((i%5)*32);x1=x-16;y1=i>4?36:4;x2=x+16;y2=y1+32;
		  html += "<area onclick='setpen("+w+")' title='"+w+"' shape=rect coords='"+x1+","+y1+","+x2+","+y2+"'>"
		  w = i>4?50+((i-3)*10):w*2; 
	   }
	   html += "</map>"; 
	   R.innerHTML = html;
	   B.innerHTML = "<img onload='loadtracersex (MAXBRUSHES,BRUSH_RESIZE);gozoom();' src='thumbnail.php?b="+T._brush+"&p="+p+"'>";
   }
} // setpen 
   

   
// colors
function grid (R,G,B,A) {
     addtolog("grid",grid);
   var colors = new Array("00","33","66","99","CC","FF");
   var html="",d=MM_findObj,ck=d("ckcolortable"),bon=ck?ck.checked:true,L=d("dcolor"),T=tools[SELECTEDTOOL];  
   var arrow = "images/arrow.gif";
   var line  = "images/line.gif";
   
   if (A) customcolor="";
   else if (customcolor!="") {
       R=customcolor.substr(0,2);
       G=customcolor.substr(2,2);
       B=customcolor.substr(4,2);
	   if (B.length<2)B="0"+B
   } 
   
   html += "<table><tr>"
   html += "<td valign=top> <div style='background-color:#"+R+G+B+";border:solid 1px black'>"
   html += "<img src='index.php?i=px' border=0 alt='"+R+G+B+"' width=24 height=24></div></td><td valign=top>"
   html += "<table cellpadding=0 cellspacing=0><tr>"
   for (r=0;r<colors.length;r++) {
      color = colors[r] + G + B;
	  chose = colors[r]==R?arrow:line;
	  html += "<td bgcolor="+color+" valign=bottom><a href=\"javascript:grid('"+colors[r]+"','"+G+"','"+B+"',1)\">"
	  html += "<img src="+chose+" border=0 alt='"+color+"' width=20 height=10>";
	  html += "</a></td>"
   }
   html += "<td>&nbsp;<input size=1 value='"+R+"' style='font:8pt tahoma;border:solid 1px'></td></tr><tr>"
   for (r=0;r<colors.length;r++) {
      color = R + colors[r] + B;
	  chose = colors[r]==G?arrow:line;
	  html += "<td bgcolor="+color+" valign=bottom><a href=\"javascript:grid('"+R+"','"+colors[r]+"','"+B+"',1)\">"
	  html += "<img src="+chose+" border=0 alt='"+color+"' width=20 height=10>";
	  html += "</a></td>"
   }
   html += "<td>&nbsp;<input size=1 value='"+G+"' style='font:8pt tahoma;border:solid 1px'></td></tr><tr>"
   for (r=0;r<colors.length;r++) {
      color = R + G + colors[r];
	  chose = colors[r]==B?arrow:line;
	  html += "<td bgcolor="+color+" valign=bottom><a href=\"javascript:grid('"+R+"','"+G+"','"+colors[r]+"',1)\">"
	  html += "<img src="+chose+" border=0 alt='"+color+"' width=20 height=10>";
	  html += "</a></td>"
   }
   html += "<td>&nbsp;<input size=1 value='"+B+"' style='font:8pt tahoma;border:solid 1px'></td></tr>"
   if (T._stroke) {
       html += "<tr><td colspan=7>";
       html += "stoke/fill options here";
       html += "</td></tr>"
   }
   html += "</table>";
   
   html = makepanel('colortable', 'Choose color', html, bon); 
    
   L.innerHTML = html;
   T._color    = R+G+B; 
   
   if ((T._brush=="Filter")&&(effects[SELECTEDFILTER]._name=="Colorize")) { T._filter = "4 "+R+G+B;T._onload(); }
   else if (T._pen) loadtracersex (MAXBRUSHES,BRUSH_REFRESH);
}

// history
var historymode = 0;
var historytext = "";
var historylast = -1;
function gethistory() { // gethistory
     addtolog("gethistory",gethistory);
   var html="";
   var d=MM_findObj,ck=d("ckagetable"),bon=ck?ck.checked:false,Y=d("historypanel"),T=tools[SELECTEDTOOL];  
  // if (ck) alert (ck.checked)
   showstatus("Loading history...");
   
   if (bon) historytext = wsdl (imageurl+"&l=log"); 
   var a       = historytext.split ("\n") 
   var last    = 0; 
   historylast = -1;
   histories   = new Array(); 
   
   if (bon) { 
        
   		for (var i=0;i<a.length;i++) {
			if (a[i].indexOf("tool")==0) {
			    histories[histories.length] = new historypoint(i,a[i]);
			}
		} 
           
        if (historymode==0) { // list view
            html += "<div style='width:180;height:140;border:solid 1px gray;overflow:auto;padding:2px;margin:2px' align=left>";
            for (var i=0;i<histories.length;i++) {
                _event = histories[i];
                history_tool = _event._data["tool"] 
			    html += "<img src='"+tools[history_tool]._icon+"' align=absmiddle>";
			    html += "<a href='javascript:advance("+(i+1)+")'>"+history_tool+"</a>";
			    html += "<br>"; 
            }
            html += "</div>";
		    html += "<div align='right'><a href='javascript:advance(-3)'>View as Thumbnails</a></div>"
		    heirsize('spagetable');
        } else { // thumbnail view
            if (historymode==-3) historymode=histories.length // -4 - Last event 
		    version = 0;
		    try {
		    
				html += "<div align=left>";
		        if (historymode==-4) { // -4 - Original image
			        historymode = 0
			        version     = -1
			        html += "Original Image"
		        } else if (histories.length) { // indicated event
		        
                    _event = histories[historymode-1];  
                    history_tool  = _event._data["tool"];
                    history_pen   = _event._data["pen"];
                    history_color = _event._data["color"];
            
				    version = _event._index; // event details
				    html += "<img src='"+tools[history_tool]._icon+"' align=absmiddle>";
				    html += "Step "+historymode+" of "+histories.length+" ("+history_tool+")<font color=gray>";
				    if (history_pen) html += "<br>&nbsp;&nbsp;&nbsp;&nbsp;Pen Size: "+history_pen;
				    if (history_color) {
					    html += "<br>&nbsp;&nbsp;&nbsp;&nbsp;Color: "+history_color;
					    html += "&nbsp;<img src='thumbnail.php?b=Bar&c="+history_color+"' align=absmiddle>";
				    }
		        } 
		        
		        html += "</div>"; // event thumbnail 
		        html += "<img src='thumbnail.php?i="+IMAGEPATH+"&w=140&r="+version+"' onload=\"heirsize('spagetable')\" align=absmiddle><br>"; 
		        if (historymode<histories.length) 
		            html += "<a style='color:blue' href='javascript:undo("+version+")'><u>Revert to this version</u></a><br>"; 
		        if (historymode>0) {
			        html += " <input type=button value='|<' onclick='advance(-4)'>";
			        html += " <input type=button value='<'  onclick='advance("+(historymode>1?-1:-4)+")'>"; 
		        }
		        if (historymode<histories.length) {
			        html += " <input type=button value='>' onclick='advance(1)'>"; 
			        html += " <input type=button value='>|' onclick='advance("+(histories.length-historymode)+")'>"; 
		        }  
		        html += "<div align='right'><a href='javascript:advance(0)'>View as List</a></div>"
		    } catch (ex) { alert ("History error: "+ex.message) }
        }   
   }
    
  
   try { 
	   html = makepanel('agetable', 'History', html, bon);er=1;
	   Y.innerHTML = html;er=2;
       d("agetable")._expand = function () { gethistory(); } 
	   er=3;
   } catch (ex) { alert (er+". "+ex.message) }
   
   if (histories.length>1) historylast=histories[histories.length-2]._index;
     hidestatus();
     
} // gethistory


function loadZoom () {
     addtolog("loadZoom",loadZoom);
    var html="",d=MM_findObj,ck=d("ckztable"),bon=ck?ck.checked:true,Y=d("navigpanel");
   
    html += "<img src='gen.jpg' id='zoompic' onload='gozoom()'><br>"; 
    row2 = ""; 
   // for (v=.125;v<4;v=v*2)  
    //     row2 += '<a href="javascript:setoffset('+( v>1?v*.75:v ) + ')">'+ 100*( v>1?v*.75:v ) +'</a> | ';
    
    row2 += "<img border=0 src='thumbnail.php?b=scaler&p="+(Hoffset*100)+"' usemap='#zoommap' id=zoomind name=zoomind>";
    
    row2 += '<input size=2 id=zoomval onfocus="this.select()" onchange="setoffset(zoomval.value/100)" '	     
    row2 += 'type=text style="font:8pt tahoma;border:solid 1px" value="'+(Hoffset*100)+'%">'
    
    
    
	   row2 += "<map name='zoommap'>" // draw pen selector image map 
	   var n=new Array(".25",".50","1","1.60","2.40","4.80","9.60");
	   for (var k=0,i=0;i<160;i+=20) {
		  x1=i;y1=0;x2=i+19;y2=24;
		  row2 += "<area href='javascript:setoffset("+n[k]+")' title='"+n[k]+"' shape=rect coords='"+x1+","+y1+","+x2+","+y2+"'>"
		  k++;
	   }
	   row2 += "</map>";
	   
	   	     
    html = makepanel('ztable', 'Zoom', html, bon, row2); 
    Y.innerHTML = html; 
}  


// zoom control
function edit_scroll () {
   if (!pr) gozoom (1)
}


function gozoom () { 
     addtolog("gozoom",gozoom);
    try {
        var d=MM_findObj,ZP=d("zoompic"),MP=d("mainpic"),DW=d("dworkspace"); 
        var Z=mboundary(ZP),M=mboundary(MP),D=mboundary(DW),ZN=d("zoompanel"); 
        var zx=Z[0],zy=Z[1],zw=Z[4],zh=Z[5],mx=M[0],my=M[1],mw=M[4],mh=M[5]; 
        var wx=D[0],wy=D[1],ww=D[4],wh=D[5],wl=DW.scrollLeft,wt=DW.scrollTop;  
		
		
        var rw=zw/mw; // ratio zoompic width to mainpic width
		var rh=zh/mh; // ratio zoompic height to mainpic height
		var nw=ww*rw; // ratio multiplied by workspace width
		var nh=wh*rh; // ratio multiplied by workspace height
		var rx=(mx-wx)*rw; // ratio multiplied by distance between mainpic left and workspace left
		var ry=(my-wy)*rh; // ratio multiplied by distance between mainpic top and workspace top  
		
		
		
        if (nw>zw) { nw=zw;rx=0; } 
        if (nh>zh) { nh=zh;ry=0; } 
		
		// decrement rx and ry by workspace scrolltop and -left
        ry-=wt*rh;rx-=wl*rw; 
		
		
		
        if (nw>0) {
	        with (ZN) {
	            style.display = "inline" 
	            style.left    = zx-rx;
	            style.top     = zy-ry;
	            style.width   = nw  
	            style.height  = nh  
	        } 
	        heirsize('spztable');
        } else { ZN.style.display="none" }
    } catch (ex) { alert ("zooming error: "+ex.message) }
}




function undo(i) { // send undo request for index "i"
     addtolog("undo",undo);
   if (i<0) i=historylast;
   if (i<0) i=0
   var h = wsdl (imageurl+"&u="+i);  
   
	var i = "i="+IMAGEPATH+"&ac=ac";
	actual = wsdl(i);
	actual = actual.split(",");  
   
   sizepic(); 
}
function advance(i) {
     addtolog("advance",advance);
   if (i==0) {
      historymode=i
   } else if (i==-2) {
      historymode=1
   } else if (i<-2) {
      historymode=i
   } else {
      historymode += i;
   }
  gethistory()
} 


 
// mouse handlers
// ---------------------------------------------------------------------------'
var pixels=new Array(),ox=0,oy=0,cx=0,cy=0,cw=6,gx=0,gy=0;dr=false,pr=false;
var pixelcount=0;
var pixelindex=0;
// mouse down
function startmq(eX,eY,eT) {
	var X=eX,Y=eY,E=eT;
	if (document.all) {
		X = window.event.x;
		Y = window.event.y; 
		E = event.srcElement; 
	} 
		
   var d=MM_findObj,EW=d("editworkspace"),ZN=d("zoompanel"),ZP=d("zoompic");
   var DW=d("dworkspace"),MP=d("mainpic"),T=tools[SELECTEDTOOL];  
	var P = mboundary (EW); 
	var Z = mboundary (ZN); 
	Px = P[0]; Py = P[1]; Pw = P[2]; Ph = P[3];	 
	Zx = Z[0]; Zy = Z[1]; Zw = Z[2]; Zh = Z[3];	 

// decrement coords by boundary of image workspace
    Rx = X-Px;
	Ry = Y-Py;
    gx=0;gy=0;
	
	
	if (inRegion(X,Y,new Array(Px,Py,Pw,Ph))==1) {
       addtolog("startmq",startmq);
	   
	   cx = X;
	   cy = Y;
	   dr = true;
	   
// increment coords by scroll position of preview pane
	   Rx += DW.scrollLeft
	   Ry += DW.scrollTop
	   
// reset pens and brushes	   
	   pixelcount=0;
	   pixels = new Array(Rx+","+Ry )
	   brush (X,Y);
	   d("tracepanel").style.display="inline";
	   if (tools[SELECTEDTOOL]._mousedown) 
	      tools[SELECTEDTOOL]._mousedown(X,Y); 
	   
	} else if (inRegion(X,Y,new Array(Zx,Zy,Zw,Zh))==1) {
	   cx = X-docx(zoompanel);
	   cy = Y-docy(zoompanel);
	   pr = true;   
	} else dr = false
}

// mousemove
function drawmq(eX,eY,eT) {
	var X=eX,Y=eY,E=eT;
	if (document.all) {
		X = window.event.x;
		Y = window.event.y; 
		E = event.srcElement; 
	} 
   var d=MM_findObj,EW=d("editworkspace"),ZN=d("zoompanel"),ZP=d("zoompic");
   var DW=d("dworkspace"),MP=d("mainpic"),T=tools[SELECTEDTOOL];   
	if ((!EW)||(!ZP)) return false;
	var P = mboundary (EW)
	var D = mboundary (ZP)
	Px = P[0]; Py = P[1]; Pw = P[2]; Ph = P[3];	  
	 
	if (pr) { // controls the navigation panel --------------------------'
		mw = X-cx;
		mh = Y-cy;
		if (mw<D[0]) mw = D[0];
		if (mh<D[1]) mh = D[1];
		if (mw+ZN.offsetWidth>D[2])  mw = D[2] - ZN.offsetWidth;
		if (mh+ZN.offsetHeight>D[3]) mh = D[3] - ZN.offsetHeight;
		
		iw = MP.offsetWidth;
		ih = MP.offsetHeight; 
		
		zw = ZP.offsetWidth;
		zh = ZP.offsetHeight; 
		
		ww = DW.offsetWidth;
		wh = DW.offsetHeight;
		
		rw = zw/iw;
		rh = zh/ih;
		
		sx = (mw-D[0]) / rw;
		sy = (mh-D[1]) / rh;
		 
		
		DW.scrollLeft = sx
		DW.scrollTop = sy
 
		
		with(ZN) {			    
			style.left    = mw; 
			style.top     = mh; 
		}	
	 } // controls the navigation panel ---------------------------------'
	 
   
	if (inRegion(X,Y,new Array(Px,Py,Pw,Ph))==1) 
	    brush (X,Y); 
    
    if (!dr) return false;

    Rx = X-Px;
	Ry = Y-Py;
	
	   
	Rx += DW.scrollLeft
	Ry += DW.scrollTop
	
	
	   
	if (pixelcount%tools[SELECTEDTOOL]._penspan==0) { 
	      pixels[pixels.length] = Rx+","+Ry; 
	} 
	
	try {
	     if (tools[SELECTEDTOOL]._pen) { 
			 fX = d ("brushpanel").style.left;
			 fY = d ("brushpanel").style.top;
			 fI = pixels.length-1;
			 
			 if (pixelcount<(MAXBRUSHES*tools[SELECTEDTOOL]._penspan)) {
				with (MM_findObj("tr"+fI)) {
					style.display = "inline";
					style.left = fX
					style.top = fY
				}
				
				if (pixelindex<MAXBRUSHES) pixelindex ++; 
				else pixelindex = 0;
			 } else showmq()
		 }	   
	} catch (ex) { }
	
	pixelcount++;
    if (tools[SELECTEDTOOL]._mousemove) { 
        tools[SELECTEDTOOL]._mousemove();
    }
}

// mouseup
function showmq (eX,eY,eT) {
	var X=eX,Y=eY,E=eT;
	if (document.all) {
		X = window.event.x;
		Y = window.event.y; 
		E = event.srcElement; 
	} 
    pr = false
    if (!dr) return false;
     addtolog("showmq",showmq);
    c = "";
	t = tools[SELECTEDTOOL];
	P = isNaN(t._pen)?1:t._pen*Hoffset;
    q = "&t="+t._brush;
	if (t._color) q += "&c="+t._color;
	if (t._pen) q += "&p="+(t._pen=="X"?10:P);
	if (t._font) q += "&f="+t._font;
	
	for (var i=0;i<pixels.length;i++) 
	     c+=(c==""?"":"/")+pixels[i];
	t._request = imageurl+"&z="+c+q; 
	if (t._mouseup) t._mouseup();	
	dr = false;
}

function brush (x,y) {
	tools[SELECTEDTOOL]._x = x;
	tools[SELECTEDTOOL]._y = y;
	// brushpanel.style.border = "solid 1px lime";
	 var B = MM_findObj ("brushpanel");
	 var W = B.offsetWidth;
	 var H = B.offsetHeight;
	 B.style.left = x-(W/2);
	 B.style.top = y-(H/2);
}

function inRegion(x,y,region) {
    var ok = 0
    if (x >= region[0]) {
        if (x <= region[2]) {
            if (y >= region[1]) {
                if (y <= region[3]) {
                    ok = 1
                }
            }
        }           
    }
    return ok
}


function saveimage() {
    var oldn = MM_findObj ("isavename").value;
    var qual = MM_findObj ("isavequal").value;
	if (MM_findObj("itypejpeg").checked) i="jpeg";
	if (MM_findObj("itypepng").checked) i="png";
	if (MM_findObj("itypegif").checked) i="gif";
    var nsrc = "thumbnail.php?"+imageurl+"&ft="+i+"&fo="+qual+"&ff="+oldn+"&fo="+qual;
	location.href=nsrc;
}


function getsavepreview(i) { 
 
	  MM_findObj ("savepic").src = "gen.jpg";
	  window.setTimeout ("getsavepreviewex('"+i+"')",500)
}
function getsavepreviewex(i) {
 
    var oldn = MM_findObj ("isavename").value;
    var qual = MM_findObj ("isavequal").value;
    var nsrc = "thumbnail.php?i="+IMAGEPATH+"&w=140&ft="+i+"&fo="+qual;
	MM_findObj ("savepic").src = nsrc;
	v = oldn.lastIndexOf (".")
	MM_findObj ("savequal").style.display=i=="jpeg"?"inline":"none";
	MM_findObj ("isavename").value = oldn.substr(0,v) + "." + i;
//	heirsize('spsavetable');
	
}


function chk(i) { return i?" checked ":""}
function dsa(i) { return i?" disabled ":""}

 

function nsstartmq(e) {   
	startmq (e.pageX ,e.pageY ,e.target )  
}

function nsdrawmq(e) { 
	drawmq (e.pageX ,e.pageY);   
}

function nsshowmq(e) { 
	showmq (e.pageX ,e.pageY);
}

if (EDITMODE=="e")
{
	if (document.all) 
	{	 
		document.body.attachEvent ("onmousedown", startmq);
		document.body.attachEvent ("onmousemove", drawmq);
		document.body.attachEvent ("onmouseup", showmq); 
	} 
	else 
	{    
		document.onmousedown = nsstartmq;
		document.onmouseup   = nsshowmq;
		document.onmousemove = nsdrawmq;
		document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE | Event.MOUSEUP | Event.KEYUP);    
	}
}
	 


